const db = require('../mysql')
const express_JWT = require('express-jwt')
const jwt = require('jsonwebtoken')
const config = require('../config/config')
const bcryptjs = require('bcryptjs')
const axios = require('axios')

exports.Register = (req, res) => {

    const userinfo = req.body
    console.log(userinfo);
    const searchSql = 'SELECT username from users where username=?'
    new Promise((resolve, reject) => {
        db.query(searchSql, userinfo.username, (err, result) => {
            if (err) reject(err)
            if (result.length === 1) {
                reject('该用户已存在，请重新输入用户名！！')
            }
            resolve(userinfo)

        })
        // promise成功的回调
    }).then(userinfo => {
        userinfo.password = bcryptjs.hashSync(userinfo.password, 10)
        const token = jwt.sign({ username: userinfo.username }, config.secretKey, { expiresIn: config.expiresTime })
        const registerSql = "INSERT INTO users(username,password) VALUE(?,?)"
        db.query(registerSql, [userinfo.username, userinfo.password], (err, result) => {
            if (err) res.cc(err)
            if (result.affectedRows === 1) {
                res.send({
                    status: 200,
                    message: '注册成功',
                    token: 'Bearer ' + token
                })
            }
        })
        // promise失败的回调
    }, reason => {
        return res.cc(reason)
    })
}

exports.Login = (req, res) => {
    const userinfo = req.body
    const searchSql = 'SELECT password from users where username=?'
    new Promise((resolve, reject) => {
        db.query(searchSql, userinfo.username, (err, result) => {
            if (err) reject(err)
            if (result.length !== 1) {
                reject('用户名错误，请重新输入！！！')
            }
            resolve({ userinfo, result })
        })
        // 成功的回调
    }).then(data => {
        const compareResult = bcryptjs.compareSync(data.userinfo.password, data.result[0].password)
        const token = jwt.sign({ username: data.userinfo.username }, config.secretKey, { expiresIn: config.expiresTime })
        if (compareResult !== true) {
            res.cc('密码错误，请重新输入！！')
        } else {
            res.send({
                status: 200,
                message: '登录成功',
                token: 'Bearer ' + token
            })
        }
        // 错误的回调
    }, err => {
        res.cc(err)
    })
}

exports.wechatLogin = async (req, res) => {
    try {
        const code = req.query.code
        const userinfo = await axios({
            method: 'get',
            url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx0a7c5c6a557a1a97&secret=a2341f0d1ae8632609aaa7bed2bb332c&js_code=${code}&grant_type=authorization_code`,
        })
        searchWechatInfo(req, res, userinfo)
    } catch (error) {
        res.cc(error)
    }

}

// 查询数据库中是否有微信授权信息
function searchWechatInfo(req, res, userinfo) {
    db.query('SELECT * from wechat_users where openid=?', userinfo.data.openid, (err, result) => {
        if (err) res.cc(err)
        // 没有微信授权信息
        if (result.length === 0) {
            const phone = getMoble()
            console.log(phone);
            const appResult = appLoginOrRegister({ phone: phone, password: userinfo.data.openid, isLogin: false })
            // 注册成功
            appResult.then(val=> {
                // 没有该用户信息时，插入用户信息
                db.query('INSERT INTO wechat_users (openid,unionid,session_key,username,password) VALUE(?,?,?,?,?)', [userinfo.data.openid, userinfo.data.unionid, userinfo.data.session_key, phone, userinfo.data.openid], (err, result) => {
                    if (err) return res.cc(err)
                    if (result.affectedRows === 1) {
                        const token = jwt.sign({ session_key: userinfo.data.session_key, openid: userinfo.data.openid, phone: phone }, config.secretKey, { expiresIn: config.expiresTime })
                        res.send({
                            status: 200,
                            message: '注册成功',
                            wechatToken: token,
                            token: val.data.token
                        })
                    } else {
                        res.send({
                            status: 401,
                            message: '注册失败',
                        })
                    }
                })
            }).catch(err=> {
                res.cc('注册失败')
            })
        } else {
            console.log('登录app');
            // 有该用户信息时，更新用户信息
            const appResult = appLoginOrRegister({ phone: result[0].username, password: result[0].password, isLogin: true })
            // 登录成功
            appResult.then(val=> {
                // 更新session_key
                db.query('UPDATE wechat_users SET session_key=? WHERE openid=?', [userinfo.data.session_key, userinfo.data.openid], (err, result2) => {
                    if (err) return res.cc(err)
                    if (result2.affectedRows === 1) {
                        const token = jwt.sign({ session_key: userinfo.data.session_key, openid: userinfo.data.openid, phone: result[0].username }, config.secretKey, { expiresIn: config.expiresTime })
                        res.send({
                            status: 200,
                            message: '注册成功',
                            wechatToken: token,
                            token: val.data.token
                        })
                    } else {
                        res.send({
                            status: 401,
                            message: '注册失败',
                        })
                    }
                })
            }).catch(err=> {
                res.cc(err)
            })
        }
    })
}
// 登录或注册微信小程序
async function appLoginOrRegister({ phone, password, isLogin }) {
    let url = isLogin ? 'https://apixi.top/index.php/api/user/login' : 'https://apixi.top/index.php/api/user/register'
    let data = isLogin ? {
        username: phone,
        password: password
    } : {
        phone: phone,
        password: password
    }
    try {
        const result = await axios({
            method: 'POST',
            url: url,
            data: data
        })
        if(result.status !==200) return false
        console.log(result.data, '成功');
        return result
    } catch (error) {
        console.log(error, '失败');
        return false
    }
}

// 随机手机号
function getMoble() {
    var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "170", "187", "189");
    var i = parseInt(10 * Math.random());
    var prefix = prefixArray[i];
    for (var j = 0; j < 8; j++) {
        prefix = prefix + Math.floor(Math.random() * 10);
    }
    return prefix;
}